<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ titles }}</span>
          <el-button size="mini" style="float: right" @click="router.go(-1)">返回</el-button>
        </div>
      </template>
      <el-form ref="form" :model="formData" label-position="left" label-width="100px" margin-left="10px">
        <el-group style="width: 600px; vertical-align: top">
          <!-- <el-radio-group v-model="formData.studio" style="margin-bottom: 15px">
            <el-radio label="一部">一部</el-radio>
            <el-radio label="二部">二部</el-radio>
            <el-radio label="三部">三部</el-radio>
          </el-radio-group> -->
          <el-form-item label="项目名称：">
            <el-input v-model="formData.product_name" @change="hasSameName" style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="部门：">
            <el-input v-model="formData.department_name" style="width: 300px; margin-right: 10px" readonly></el-input>
            <el-button @click="openDepartmentList">选择部门</el-button>
          </el-form-item>

          <el-form-item label="参与人员：">
            <el-input v-model="formData.member" style="width: 300px; margin-right: 10px" readonly></el-input>
            <el-button @click="openMemberList">选择人员</el-button>
          </el-form-item>
          <el-form-item label="经营：">
            <el-input v-model="formData.money" style="width: 150px" type="number"></el-input>&nbsp;&nbsp;元
          </el-form-item>

          <el-form-item label="开始日期：">
            <el-date-picker v-model="formData.work_date" type="date" placeholder="选择日期"
              style="width: 150px"></el-date-picker>
          </el-form-item>

          <el-form-item label="截止日期：">
            <el-date-picker v-model="formData.deadline_date" type="date" placeholder="选择日期"
              style="width: 150px"></el-date-picker>
          </el-form-item>

          <el-form-item label="紧急程度：">
            <el-radio-group v-model="formData.level">
              <el-radio label="1" size="large">非常紧急</el-radio>
              <el-radio label="2" size="large">正常项目</el-radio>
              <el-radio label="3" size="large">长期项目</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="已完成：">
            <el-switch v-model="formData.progress" :active-value="100" :inactive-value="0" class="ml-2"
              style="--el-switch-on-color: #13ce66; " />
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="formData.notes" style="width: 400px" type="textarea" :rows="5"></el-input>
          </el-form-item>
          <el-form-item label="项目总工分：">
            <el-input v-model="formData.total_score" style="width: 150px" type="number"></el-input>&nbsp;&nbsp;（用于后续打分）
          </el-form-item>
        </el-group>

        <el-group class="el-group-complete">
          <div class="files">
            <div style="color: rgba(184, 32, 32, 0.699); margin-bottom: 20px">
              *请勾选数量
            </div>
            <el-form-item label="海报设计：">
              <el-input-number v-model="formData.haibao" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="长图设计：">
              <el-input-number v-model="formData.changtu" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="H5设计：">
              <el-input-number v-model="formData.h5" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="视频制作：">
              <el-input-number v-model="formData.shipin" :min="0" style="width: 150px" />
            </el-form-item>
            <el-form-item label="资源图：">
              <el-input-number v-model="formData.ziyuan" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="插画：">
              <el-input-number v-model="formData.chahua" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="动画：">
              <el-input-number v-model="formData.donghua" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="PPT、杂志">
              <el-input-number v-model="formData.ppt" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="物料：">
              <el-input-number v-model="formData.wuliao" :min="0" style="width: 150px" />
            </el-form-item>
            <!-- <el-form-item label="文件：">
              <el-upload v-model:file-list="formData.fileList" class="upload-demo" :action="`${baseURL}/api/upload`"
                :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" multiple :name="'files'"
                list-type="picture">
                <el-button type="primary">点击上传</el-button><span style="padding-left: 10px; font-size: 10px; color: gray">
                  可同时上传多个文件
                </span>
              </el-upload>
            </el-form-item> -->
            <!-- <el-form-item label="已上传文件：" v-show="hasFileList.length > 0">
              <ul class="hasFileList">
                <li v-for="(file, index) in hasFileList" :key="index">
                  <template v-if="tool.isImage(file.url)">
                    <el-image :src="`${baseURL}/${file.url}`" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                      :preview-src-list="file.url.split(',').map((url) => `${baseURL}/${url.trim()}`)
                        " :initial-index="0" fit="cover" @load="onImageLoad" />
                  </template>
                  <template v-else-if="tool.isVideo(file.url)">
                    <video controls :src="`${baseURL}/${file.url}`" class="video" preload="metadata"></video>
                  </template>
                  <template v-else>
                    <a :href="`${baseURL}/${file.url}`" class="file-download" target="_blank">
                      <el-button type="primary" round>
                        点击查看{{ file.url.split('/').pop().split('.').pop() }}文件<el-icon class="el-icon--right">
                          <View />
                        </el-icon>
                      </el-button>
                    </a>
                  </template>
                  <el-button type="danger" :icon="Delete" circle @click="delFile(file.id)" />
                </li>
              </ul>
            </el-form-item> -->
          </div>
        </el-group>

        <el-form-item>
          <el-button type="primary" @click="open" style="width: 100px">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog v-model="departmentDialogVisible" title="选择部门" @closed="handleDialogClosed">
      <el-button-group v-model="selectedDepartments">
        <el-button v-for="department in departments" :key="department.id" :type="selectedDepartments === department.name ? 'primary' : 'default'
          " @click="toggleDepartment(department.name)">
          {{ department.name }}
        </el-button>
      </el-button-group>
    </el-dialog>

    <el-dialog v-model="memberDialogVisible" title="选择人员">
      <el-button-group v-model="selectedMember">
        <el-button v-for="member in members" :key="member.id"
          :type="selectedMember.includes(member.name) ? 'primary' : 'default'" @click="toggleMember(member.name)">
          {{ member.name }}
        </el-button>
      </el-button-group>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirmMemberDialog">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="nameDialogVisible" title="已有类似项目，名称为：" :before-close="handleClose" class="nameDialog" width="500">
      <template v-if="similarWorks && similarWorks.length > 0">
        <ul>
          <el-popover v-for="item in similarWorks" placement="top" width="200" trigger="hover">
            <div v-html="generateContent(item)"></div>
            <template #reference>
              <li>{{ item.product_name }}</li>
            </template>
          </el-popover>
        </ul>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="nameDialogVisible = false">
            知道了
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { Minus, Plus } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import workApi from '../../api/work'
import fileApi from '../../api/file'
const router = useRouter()
const route = useRoute()
const isComplete = ref(false) //部分字段在完成时再填写
const isEdit = ref(false)
const formData = ref({
  studio: '',
  product_name: '',
  department_name: '',
  member: '',
  haibao: '',
  changtu: '',
  h5: '',
  shipin: '',
  ziyuan: '',
  chahua: '',
  donghua: '',
  ppt: '',
  wuliao: '',
  money: '',
  work_date: '',
  deadline_date: '',
  progress: 0,
  notes: '',
  bianji_proportion: '',
  sheji_proportion: '',
  jishu_proportion: '',
  fileList: [],
  level:'',
  total_score:''
})
const hasFileList = ref([])   //已经存在的数据

const departmentDialogVisible = ref(false)
const memberDialogVisible = ref(false)
const nameDialogVisible = ref(false)
const selectedDepartments = ref([])
const selectedMember = ref([])
const departments = ref([])
const members = ref([])
const titles = ref()
const similarWorks = ref([])
// 获取全局变量
const baseURL = window.globalConfig.baseURL
//打开选择部门窗口
const openDepartmentList = async () => {
  departmentDialogVisible.value = true
  selectedDepartments.value = formData.value.department_name
}

const toggleDepartment = (name) => {
  departmentDialogVisible.value = false
  formData.value.department_name = name
  selectedDepartments.value = name
}

//打开选择人员窗口
const openMemberList = async () => {
  memberDialogVisible.value = true
  selectedMember.value = Object.assign([], formData.value.member)
}

//点击人员
const toggleMember = (name) => {
  // 将逗号隔开的字符串转换为数组
  const membersArray = selectedMember.value

  if (membersArray.includes(name)) {
    // 如果名字已经存在，从数组中移除
    const index = membersArray.indexOf(name)
    membersArray.splice(index, 1)
  } else {
    // 如果名字不存在，添加到数组中
    membersArray.push(name)
  }
  // 更新 selectedMember 的值，将数组转换为逗号隔开的字符串
  selectedMember.value = membersArray
}

//选人对话框，点击确定
const confirmMemberDialog = () => {
  memberDialogVisible.value = false
  formData.value.member = Object.assign([], selectedMember.value)
}

const open = () => {
  ElMessageBox.confirm(
    '确认提交吗？',
    '温馨提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '返回',
      type: 'warning',
    }
  )
    .then(() => {
      submitForm()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消提交',
      })
    })
}

const submitForm = async () => {
  //判断是否正确输入
  if (!formData.value.product_name || !formData.value.department_name) {
    ElMessage.warning('请填写项目名称和部门')
    return
  }

  const username = sessionStorage.getItem('username') //日志需要

  if (isEdit.value) {
    const data = {
      id: route.query.id,
      data: formData.value,
      username: username,
    }
    
    //把member的数组转成字符串
    if (
      formData.value.member != '' &&
      typeof formData.value.member !== 'string'
    ) {
      formData.value.member = formData.value.member.join(',')
    }

    //把开始日期转化成时间格式
    if (formData.value.work_date != "" && formData.value.work_date) {
      const workDate = new Date(formData.value.work_date);
      formData.value.work_date = formatDateToLocalString(workDate);
    } else {
      formData.value.work_date = null;
    }
    //把截止日期转化成时间格式
    if (formData.value.deadline_date != "" && formData.value.deadline_date) {
      const deadlineDate = new Date(formData.value.deadline_date);
      formData.value.deadline_date = formatDateToLocalString(deadlineDate);
    } else {
      formData.value.deadline_date = null;
    }

    if (formData.value.progress) {
      formData.value.progress = '100'
    } else {
      formData.value.progress = '0'
    }
    const res = await workApi.updateOrder(data)
    // 处理后台返回的结果，你可以根据具体情况进行处理
    if (res.data.success) {
      ElMessage.success('更新成功')
      router.go(-1)
      // router.push('/week_report')
    } else {
      ElMessage.error('更新失败')
    }
  } else {
    // 新增，提交到后台
    //把member的数组转成字符串
    if (
      formData.value.member != '' &&
      typeof formData.value.member !== 'string'
    ) {
      formData.value.member = formData.value.member.join(',')
    }

    //把开始日期转化成时间格式
    if (formData.value.work_date != "" && formData.value.work_date) {
      const workDate = new Date(formData.value.work_date);
      formData.value.work_date = formatDateToLocalString(workDate);
    } else {
      formData.value.work_date = null;
    }

    //把截止日期转化成时间格式
    if (formData.value.deadline_date != "" && formData.value.deadline_date) {
      const deadlineDate = new Date(formData.value.deadline_date);
      formData.value.deadline_date = formatDateToLocalString(deadlineDate);
    } else {
      formData.value.deadline_date = null;
    }

    formData.value.username = username
    if (formData.value.progress) {
      formData.value.progress = '100'
    } else {
      formData.value.progress = '0'
    }

    const res = await workApi.addOrder(formData.value)
    // 处理后台返回的结果，你可以根据具体情况进行处理
    if (res.data.id) {
      ElMessage.success('新增成功')
      router.go(-1)
      // router.push('/week_report')
    } else {
      ElMessage.error('新增失败')
    }
  }
}
onMounted(async () => {
  //请求部门列表
  const departmentRes = await workApi.getDepartments()
  departments.value = departmentRes.data
  //请求人员列表
  const memberRes = await workApi.getMembers()
  members.value = memberRes.data
  if (route.query.id) {
    //请求数据
    const orderRes = await workApi.getOrder({ id: route.query.id })
    console.log(orderRes.data[0])
    Object.assign(formData.value, orderRes.data[0])
    if (formData.value.progress == "100") {
      formData.value.progress = 100
    } else {
      formData.value.progress = 0
    }
    // formData.value.work_date = new Date()
    // formData.value.deadline_date = new Date()
    // 初始化成员
    if (orderRes.data[0].member) {
      if (orderRes.data[0].member.includes(',')) {
        formData.value.member = Object.assign(
          [],
          orderRes.data[0].member.split(',')
        )
      } else {
        formData.value.member = Object.assign([], [orderRes.data[0].member])
      }
    }

    titles.value = '编辑项目'
    isEdit.value = true
    //以下部分是从已完成项目列表中点进来的，所以progress都是100
    // if (formData.value.progress == '100') {
    //   isComplete.value = true
    //   const fileRes = await fileApi.getFilesById({ id: route.query.id })
    //   hasFileList.value = fileRes.data
    // }
  } else {
    titles.value = '新增项目'
  }
})

const toComplete = () => {
  formData.value.progress = 100
  isComplete.value = true
}

const increase = () => {
  formData.value.progress += 20
  console.log(formData.value.progress)
  if (formData.value.progress >= 100) {
    formData.value.progress = 100
    isComplete.value = true
  } else {
    isComplete.value = false
  }
}
const decrease = () => {
  isComplete.value = false
  formData.value.progress -= 20
  if (formData.value.progress < 0) {
    formData.value.progress = 0
  }
}

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePreview = (file) => {
  console.log(file)
}

const handleSuccess = () => {
  console.log(formData.value.fileList)
}

const hasSameName = async () => {
  if (formData.value.product_name != '') {
    const res = await workApi.getRecentWorks()
    // 检查 res.data 是否存在
    if (res.data) {
      similarWorks.value = [] // 新数组用于存储符合条件的项目对象
      // 遍历 res.data 数组中的每个项目对象
      res.data.forEach((item) => {
        if (hasSameThreeChars(item.product_name, formData.value.product_name)) {
          // 如果符合条件，则将项目对象添加到新数组中
          similarWorks.value.push(item)
        }
      })
      if (similarWorks.value.length > 0) {
        nameDialogVisible.value = true
      }
    }
  }
}

// 辅助函数：检查两个字符串是否具有相同的任意位置的三个中文字符
const hasSameThreeChars = (str1, str2) => {
  // 检查字符串长度是否小于 3，如果是，则无法比较
  if (str1.length < 3 || str2.length < 3) {
    return false
  }

  // 正则表达式，匹配中文字符
  const chineseRegex = /[\u4e00-\u9fa5]/

  // 遍历第一个字符串中的字符
  for (let i = 0; i <= str1.length - 3; i++) {
    const subStr1 = str1.substring(i, i + 3) // 获取第一个字符串的三个字符子串

    // 如果不包含中文字符，则跳过当前子串
    if (!chineseRegex.test(subStr1)) {
      continue
    }

    // 遍历第二个字符串中的字符
    for (let j = 0; j <= str2.length - 3; j++) {
      const subStr2 = str2.substring(j, j + 3) // 获取第二个字符串的三个字符子串

      // 如果不包含中文字符，则跳过当前子串
      if (!chineseRegex.test(subStr2)) {
        continue
      }

      // 如果两个子串相等，则表示找到了相同的任意位置的三个中文字符，返回 true
      if (subStr1 === subStr2) {
        return true
      }
    }
  }

  // 没有找到相同的任意位置的三个中文字符，返回 false
  return false
}

const generateContent = (item) => {
  if (item) {
    return `成员：${item.member}</br>进度：${item.progress}%`
  } else {
    return '暂无项目'
  }
}


const delFile = async (id) => {
  ElMessageBox.confirm('确定要删除该文件吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const username = sessionStorage.getItem('username')
      const res = await fileApi.delFile({ id: id, username: username })
      if (res.data.success) {
        ElMessage.success('删除成功')
        const fileRes = await fileApi.getFilesById({ id: route.query.id })
        hasFileList.value = fileRes.data
      } else {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const formatDateToLocalString = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style scoped>
.el-button-group {
  vertical-align: baseline;
}

el-group {
  position: relative;
  padding-left: 10px;
  display: inline-block;
}

.el-group-complete .proportion {
  margin: 10px 0 30px 90px;
  padding: 30px;
  border-radius: 20px;
  background: rgb(255 255 255);
  box-shadow: rgba(0, 0, 0, 0.45) 0px 5px 40px 0px;
}

.el-group-complete .files {
  margin: 10px 0 30px 90px;
  padding: 30px;
  border-radius: 20px;
  background: rgb(255 255 255);
  box-shadow: rgba(0, 0, 0, 0.45) 0px 5px 40px 0px;
  max-width: 600px;
  width: 300px;
}

.el-progress--line {
  margin-bottom: 15px;
  width: 248px;
}

.nameDialog li {
  cursor: pointer;
  margin-bottom: 10px;
  text-decoration: underline;
}

.upload-demo {
  width: 300px;
}

.el-input__inner {
  text-align: center;
}

.hasFileList {
  width: 250px;
  /* height: 200px; */
  /* line-height: 200px; */
  overflow: hidden;
  cursor: pointer;
  display: inline-block;
  padding: 0;
}

.hasFileList li {
  list-style: none;
  position: relative;
}

.hasFileList .el-image {
  width: 70%;
  display: inline-block;
}

.hasFileList li video {
  width: 70%;
  object-fit: contain;
  height: 100%;
  margin: 10px
}

.el-button.is-circle {
  position: absolute;
  top: 50%;
  margin-top: -20px;
  margin-left: 20px;
}


@media screen and (max-width: 768px) {
  .el-card {
    overflow: auto;
  }
}
</style>
